const app = getApp();
const util = require('../../../utils/util.js');
const lbbService = require('../../../pages/service/service.js');
const lbbTaskService = require('../service/task-service.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        activeKey:0,
        active:0,
        dataValues: {
            // 闲置查询参数
            provinceId:'',
            cityId:'',
            districtId:'',
            hosLevel:'',
            hosName:'',            
            minOutpatientNum:'',
            maxOutpatientNum:'',
            statusTime:'',
            unusedRate:'',
            // 调度参数
            type:'',
            handelTime:'',
            pageNo:1,
            pageSize:10
        },
        show:false,
        userList: [],
        companyTypeList:[],
        sourceList: [],
        projectList: [],
        showContacts: false,
        contactObj: {},
        contactTypeList: [],
        timeMarketList: [
            {
                text:'>=1个月',
                value:'1'
            },
            {
                text:'>=1年',
                value:'12'
            },
            {
                text:'>=2年',
                value:'24'
            }
        ],
        usedDayList:[
            { 
                text:'连续3天',
                value:'3'
            },
            { 
                text:'连续5天',
                value:'5'
            },
            { 
                text:'连续7天',
                value:'7'
            },
        ],
        deviceCountList:[
            { 
                text:'大于等于1台',
                value:'1'
            },
            { 
                text:'大于等于3台',
                value:'3'
            },
            { 
                text:'大于等于5台',
                value:'5'
            },
        ],
        vacancyRateList:[
            {
                text:'>=40',
                value:'40'
            },
            {
                text:'>=50',
                value:'50'
            },
            {
                text:'>=60',
                value:'60'
            }
        ],
        schedulingTypeList:[
            {
                text:'院内调度',
                value:0
            },
            {
                text:'院外调度',
                value:1
            },
            {
                text:'撤场',
                value:2
            },
        ],
        hospitalList:[
            {
                hospitalName:'1',
                hospitalId:1
            }
        ],
        finished:false,

        showMarkInfo:false,
        minDate:new Date(2010, 0, 1).getTime(),
        currentDate:new Date().getTime(),
        remarkFormData:{
            id:'',
            markType:-1,
            markTime:'',
            remark:''
        },
        markShow:false,

        showRemark:false,
        dispatchFormData:{
            position:'',
            dispatchRemark:''
        },

        dispatchInfo:false,
        
        // 分页参数
        background:"#F4F4F4",
        loading: true,
        loaded: false,
        isBackBtn: true, // 设置是否显示回到顶部按钮
        defaultSetting: {
            shake: true, // 设置是否开启震动
            style: "black", // 设置圆点申诉还是浅色
        },
        ldleHospitalList:[],
        dispatchHospitalList:[],
        // 时间显示
        dateTimeShow:false,

        onBeforeClose(action, done) {
            if (action == 'confirm') {
                return false
            } else {
                return true
            }
        },
    },
    //上拉加载更多
    eventhandle(e) {
        let that = this
        let pagenum = Number(that.data.dataValues.pageNo)
        if (pagenum >= that.data.TotalPage) {
            that.setData({
                loading: false,
                loaded: true
            })
        } else {
            pagenum = pagenum + 1
            that.data.dataValues.pageNo = pagenum.toString()
            that.setData({
                loading: true,
                loaded: false,
                dataValues:that.data.dataValues
            })
            if(that.data.active==0){
                that.getldleList()
            } else {
                that.getDispatch()
            }
        }
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        //获取系统的参数，scrollHeight数值,微信必须要设置style:height才能监听滚动事件
        wx.getSystemInfo({
        success: function (res) {
            that.setData({
            scrollHeight: parseInt(res.windowHeight)+200
            })
        }
        });
        that.getProjectList('hospital_level')
        that.getCitys()
    },
    onDisplay() {
        this.setData({ show: true });
    },
    onClose() {
        this.setData({ show: false });
    },
    dispatchFormatDate(date) {
        date = new Date(date);
        return `${date.getYear() +1900 }/${date.getMonth() + 1}/${date.getDate()}`;
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getYear() +1900 }-${date.getMonth() + 1}`;
    },
    onConfirm(event) {
        this.data.dataValues.handelTime = this.dispatchFormatDate(event.detail)
        this.setData({
          show: false,
          dataValues: this.data.dataValues
        });
    },
    onMarkDisplay() {
        this.setData({ markShow: true });
    },
    onMarkClose() {
        this.setData({ markShow: false });
    },
    onMarkConfirm(event) {
        this.data.remarkFormData.markTime = this.formatDate(event.detail)
        this.setData({
          markShow: false,
          remarkFormData: this.data.remarkFormData
        });
     },

     onDateTimeShow() {
        this.setData({ dateTimeShow: true });
    },
    onDateTimeClose() {
        this.setData({ dateTimeShow: false });
    },
    onDateTimeConfirm(event) {
        this.data.dataValues.dateTime = this.formatDate(event.detail)
        this.setData({
          dateTimeShow: false,
          dataValues: this.data.dataValues
        });
     },
    //事件处理函数
    myEventListener: function (e) {
        let that = this
        console.log(e.detail)
        if(e.detail[0]!=0){
            that.data.dataValues['provinceId']=e.detail[0]
        } 
        if(e.detail[1]!=0){
            that.data.dataValues['cityId']=e.detail[1]
        }
        if(e.detail[2]!=0){
            that.data.dataValues['districtId']=e.detail[2]
        }
        if(e.detail[3]!=0){
            that.data.dataValues['hosLevel']=e.detail[3]
        }
        that.setData({
            selectorArray: e.detail,
            dataValues:that.data.dataValues
        })
    },
    
    getCitys: function () {
        let that = this;
        lbbTaskService.getAreaList({}, function (res) {
            that.setData({
              propArray: res.data,
            })
        })
    },
    //获取数据字典
    getProjectList(code) {
        let that = this
        lbbTaskService.getDictByCode({
            code: code
        }, function (res) {
            if(code == 'hospital_level'){
                that.setData({
                    userList:res.data
                })
            }
        })
    },
    // 闲置查询列表
    getldleList(){
        let that = this
        let parmas = {
            pageNo:that.data.dataValues.pageNo,
            pageSize:that.data.dataValues.pageSize
        }
        if(that.data.dataValues.provinceId){
            parmas['provinceId'] = that.data.dataValues.provinceId
        }
        if(that.data.dataValues.cityId) {
            parmas['cityId'] = that.data.dataValues.cityId
        }
        if(that.data.dataValues.districtId) {
            parmas['districtId'] = that.data.dataValues.districtId
        }
        if(that.data.dataValues.hosLevel) {
            parmas['hosLevel'] = that.data.dataValues.hosLevel
        }
        if(that.data.dataValues.hosName) {
            parmas['hosName'] = that.data.dataValues.hosName
        }
        if(that.data.dataValues.minOutpatientNum!='') {
            parmas['minOutpatientNum'] = that.data.dataValues.minOutpatientNum
        }
        if(that.data.dataValues.maxOutpatientNum!='') {
            parmas['maxOutpatientNum'] = that.data.dataValues.maxOutpatientNum
        }
        if(that.data.dataValues.statusTime) {
            parmas['statusTime'] = that.data.dataValues.statusTime
        }
        if(that.data.dataValues.unusedRate) {
            parmas['unusedRate'] = that.data.dataValues.unusedRate
        }
        wx.showLoading({
          title: '加载中',
        })
        lbbTaskService.getUnUsedList(parmas,function(res){
            if(that.data.dataValues.pageNo==1) {
                let lists = [ ...res.data.records]
                if(lists.length==0) {
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        ldleHospitalList:lists
                    })
                    wx.hideLoading()
                } else {
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        ldleHospitalList:lists
                    })
                    wx.hideLoading()
                }
            } else {
                let lists = [...that.data.ldleHospitalList, ...res.data.records]
                console.log(lists)
                if(lists.length==0) {
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        ldleHospitalList:lists
                    })
                    wx.hideLoading()
                } else {
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        ldleHospitalList:lists
                    })
                    wx.hideLoading()
                }
            }

        })
    },
    // 调度情况列表
    getDispatch(){
        let that = this
        let parmas = {
            pageNo:that.data.dataValues.pageNo,
            pageSize:that.data.dataValues.pageSize
        }
        if(that.data.dataValues.provinceId){
            parmas['provinceId'] = that.data.dataValues.provinceId
        }
        if(that.data.dataValues.cityId) {
            parmas['cityId'] = that.data.dataValues.cityId
        }
        if(that.data.dataValues.districtId) {
            parmas['districtId'] = that.data.dataValues.districtId
        }
        if(that.data.dataValues.hosLevel) {
            parmas['hosLevel'] = that.data.dataValues.hosLevel
        }
        if(that.data.dataValues.handelTime) {
            parmas['handelTime'] = that.data.dataValues.handelTime
        }
        if(that.data.active==1) {
            parmas['dispatchState'] = 0
        } else if(that.data.active==2) {
            parmas['dispatchState'] = 1
        }
        wx.showLoading({
            title: '加载中',
        })
        lbbTaskService.getDispatchList(parmas,function(res){
            console.log('---------------->',res)
            if(that.data.dataValues.pageNo==1) {
                let lists = [...res.data.records]
                if(lists.length==0){
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        dispatchHospitalList:lists
                    })
                    wx.hideLoading()
                } else{
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        dispatchHospitalList:res.data.records
                    })
                    wx.hideLoading()
                }
            } else {
                let lists = [...that.data.dispatchHospitalList, ...res.data.records]
                if(lists.length==0){
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        dispatchHospitalList:res.data.records
                    })
                    wx.hideLoading()
                } else{
                    that.setData({
                        loading: false,
                        loaded: true,
                        TotalPage:res.data.pages,
                        dispatchHospitalList:res.data.records
                    })
                    wx.hideLoading()
                }
            }
            
            
        })
    },
    //根据code获取分类字典
    getAllCategoryAndSubList(code){
        let that=this
        lbbTaskService.getAllCategoryAndSubList({code},function(res){
            that.setData({
                companyTypeList:res.data
            })
        })
    },
    inputStartCode(e) {
        let input = e.detail.value
        let regex = /^\d+$/;
        if (!regex.test(input)) {
            wx.showToast({
                title: '请输入数字',
            })
            this.data.dataValues.minOutpatientNum = ''
            this.setData({
                dataValues:this.data.dataValues
            })
            return
        }

        this.data.dataValues.minOutpatientNum = e.detail.value
        if (this.data.dataValues.maxOutpatientNum && this.data.dataValues.maxOutpatientNum < input) {
            wx.showToast({
                title: '起始不可大于结束',
            })
            return
        }
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    inputEndCode(e) {
        let input = e.detail.value
        let regex = /^\d+$/;
        if (!regex.test(input)) {
            wx.showToast({
                title: '请输入数字',
            })
            this.data.dataValues.maxOutpatientNum = ''
            this.setData({
                dataValues:this.data.dataValues
            })
            return
        }

        this.data.dataValues.maxOutpatientNum = e.detail.value
        console.log(this.data.dataValues)
        if (this.data.dataValues.minOutpatientNum && this.data.dataValues.minOutpatientNum > input) {
            wx.showToast({
                title: '结束不可小于起始',
            })
            return
        }
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    // tab切换
    tabChange(e){
        let that = this
        that.data.dataValues.pageNo =1
        this.setData({
            active:e.detail.index,
            dataValues:that.data.dataValues
        })
        that.reset()
        if(that.data.active==0) {            
            that.getldleList()
        } else {
            that.getDispatch()
        }
    },
    //医院名称
    onChangeName(e) {
        this.data.dataValues.hosName = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    // 租金
    onChangeRentMoney(e) {
        let val = e.detail.replace(/(^\s*)|(\s*$)/g, "")
        if (!val) {
            return ''
        }
        var reg = /[^\d.]/g
        // 只能是数字和小数点，不能是其他输入
        val = val.replace(reg, "")
        // // 保证第一位只能是数字，不能是点
        val = val.replace(/^\./g, "");
        // // 小数只能出现1位
        val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        // // 小数点后面保留2位
        val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
        console.log(val)
        if (!val) {
            wx.showToast({
                title: '请输入数字',
            })
            return
        }
        this.data.dataValues.rentAmount = val
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    reset() {
        let that = this
        let childObj =that.selectComponent('.my-select')
        let childObj1 = that.selectComponent('.my-select1')
        let childObj2 = that.selectComponent('.my-select2')
        childObj.setData({
            cityShow: '0',
            provIndex: 0,
            cityIndex: 0,
            regionIndex: 0,
            provId: 0,
            cityId: 0,
            regionId: 0,
            userName: '全部等级',
            provName: '全部省',
            cityName: '全部市',
            regionName: '全部区/县',
            prov_animationData: {}, 
            city_animationData: {}, 
            region_animationData: {},
            user_animationData: {},
        })
        childObj1.setData({
            cityShow: '0',
            provIndex: 0,
            cityIndex: 0,
            regionIndex: 0,
            provId: 0,
            cityId: 0,
            regionId: 0,
            userName: '全部等级',
            provName: '全部省',
            cityName: '全部市',
            regionName: '全部区/县',
            prov_animationData: {}, 
            city_animationData: {}, 
            region_animationData: {},
            user_animationData: {},
        })
        childObj2.setData({
            cityShow: '0',
            provIndex: 0,
            cityIndex: 0,
            regionIndex: 0,
            provId: 0,
            cityId: 0,
            regionId: 0,
            userName: '全部等级',
            provName: '全部省',
            cityName: '全部市',
            regionName: '全部区/县',
            prov_animationData: {}, 
            city_animationData: {}, 
            region_animationData: {},
            user_animationData: {},
        })
        that.setData({
            dataValues:{
                // 闲置查询参数
                provinceId:null,
                cityId:null,
                districtId:null,
                hosLevel:null,
                hosName:null,            
                minOutpatientNum:'',
                maxOutpatientNum:'',
                statusTime:'',

                // 调度参数
                type:-1,
                handelTime:null,
                pageNo:1,
                pageSize:10
            }
        })
        that.reload()
    },
    reload() {
        let that = this
        that.data.dataValues.pageNo =1
        that.setData({
            dataValues:that.data.dataValues
        })
        if(that.data.active==0) {
            that.getldleList()
        } else {
            that.getDispatch()
        }
    },
    //打开公司类型选择
    onBindCompanyType(){
        this.setData({
            showCompanyType:true
        })
    },
    // 切换省份
    onChangeProvId(e) {
        let that = this
        this.data.dataValues.provinceId = e.detail.id
        this.data.dataValues.cityId = ''
        this.data.dataValues.districtId = ''
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    // 切换城市
    onChangeCityId(e) {
        let that = this
        this.data.dataValues.cityId = e.detail.id
        this.data.dataValues.districtId = ''
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    // 切换区/县
    onChangeRegion(e) {
        let that = this
        this.data.dataValues.districtId = e.detail.id
        this.setData({
            dataValues:this.data.dataValues
        })
    },
    //代理公司类型选择回调
    onClickItem(e){
        this.data.dataValues.agentCompanyTypeText = e.detail.text
        this.data.dataValues.agentCompanyType = e.detail.id
        this.data.dataValues.agentParentCompanyType =this.data.companyTypeList[e.detail.index].id
        this.data.dataValues.mainActiveIndex = e.detail.index
        this.setData({
            showInteractPerson: false,
            dataValues: this.data.dataValues
        })
    },
    //投放时间
    onChangeSource(e) {
        console.log(e)
        this.data.dataValues.statusTime = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    // 未租借筛选
    onChangeUnUsedDay(e) {
        console.log(e)
        this.data.dataValues.unUsedDay = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    // 
    onChangeDeviceCount(e) {
        console.log(e)
        this.data.dataValues.deviceCount = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    // 位置闲置率
    onChangeVacancyRate(e) {
        this.data.dataValues.unusedRate = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    // 调度类型
    onChangeType(e) {
        this.data.dataValues.type = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    //所属项目
    onChangeCheckbox(e) {
        this.data.dataValues.projectType = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    //代理类型
    onChangeAgentType(e){
        this.data.dataValues.agentType = e.detail
        this.setData({
            dataValues: this.data.dataValues
        })
    },
    showRemark(e) {
        this.resetMarkInfo()
        this.data.remarkFormData.id = e.target.dataset.id
        this.data.remarkFormData.markType = 0
        this.setData({
            showMarkInfo:true,
            remarkFormData:this.data.remarkFormData
        })
    },
    resetMarkInfo() {
        this.setData({
            remarkFormData:{
                id:'',
                markType:'',
                markTime:'',
                remark:''
            }
        })
    },
    showPositionRemark(e){
        this.setData({
            showRemark:true,
            dispatchFormData:{
                position:e.target.dataset.position,
                dispatchRemark:e.target.dataset.dispatchremark
            }
        })
    },
    //打开新增联系人
    addContacts() {
        this.setData({
            showContacts: true
        })
    },
    //联系人姓名回调
    onChangeUserName(e) {
        this.data.contactObj.name = e.detail
        this.setData({
            contactObj: this.data.contactObj
        })
    },
    //打开联系方式列表
    onBindcontactType(e) {
        this.setData({
            contactTypeIfShow: true
        })
    },
    //选择联系方式
    okContactType(e) {
        this.data.contactObj.contactTypeText = e.detail.name
        this.data.contactObj.contactType = e.detail.id
        this.setData({
            contactTypeIfShow: false,
            contactObj: this.data.contactObj
        })
    },
    //标记类型
    onChangeMarkType(e) {
        this.data.remarkFormData.markType = e.detail
        this.setData({
            remarkFormData: this.data.remarkFormData
        })
    },
   //取消标记
   onCloseContacts() {
        this.resetMarkInfo()
        this.setData({
            showMarkInfo:false,
        })
    },
   //确定处理标记
   onConfirmContacts() {
       let that=this
        if (that.data.remarkFormData.markType!=-1 && that.data.remarkFormData.markTime ) {
            let params = that.data.remarkFormData
            wx.showLoading({
              title: '加载中',
            })
            lbbTaskService.markPosition(params,function(res){
                wx.hideLoading()
                that.onCloseContacts()
                that.reload()
            })
        } else {
            this.openPrompt()
        }
    },
    onConfirmRemark() {
        this.setData({
            showRemark:false
        })
    },
    // 备注
    updateMarkRemark(e) {
        this.data.remarkFormData.remark = e.detail.value
        this.setData({
            remarkFormData: this.data.remarkFormData
        })
    },
    dispatchHospital(e) {
        let formData = [] 
        e.target.dataset.deskdispatchpositions.forEach(item =>{
            formData.push({
                id:item.id,
                position:item.position,
                dispatchState:item.dispatchStat,
                dispatchRemark:''
            })
        })
        this.setData({
            dispatchInfo:true,
            hosForm:formData
        })
    },
    onChangeDispatchState(e) {
        console.log(e)
        let index = e.target.dataset.index
        if(this.data.hosForm[index].dispatchState==0) {
            this.data.hosForm[index].dispatchState=3
        } else {
            this.data.hosForm[index].dispatchState=0
        }
        console.log(this.data.hosForm)
        // this.data.hosForm[index].dispatchState = e.detail
        this.setData({
            hosForm:this.data.hosForm
        })
    },
    updateDispatchRemark(e) {
        let index = e.target.dataset.index
        this.data.hosForm[index].dispatchRemark = e.detail.value
        this.setData({
            hosForm:this.data.hosForm
        })
    },
    validateHosForm() {
        let validate = true
        for(let i=0;i<this.data.hosForm.length;i++) {
            if(this.data.hosForm[i].dispatchState==-1){
                validate = false
            }
        }
        return validate
    },
    onConfirmDispatch(e) {
        let that = this
        let formData = this.data.hosForm
        if(this.validateHosForm()){
            wx.showLoading({
              title: '加载中',
            })
            lbbTaskService.dispatchPosition(formData,function(res){
                wx.hideLoading()
                that.setData({
                    dispatchInfo:false
                })
                that.reload()
            })
        } else {
            that.openPrompt()
        }
    },
    onCloseDispatch() {
        this.setData({
            dispatchInfo:false,
            hosForm:{},
        })
    },
    //校验提示
    openPrompt() {
        wx.showToast({
            title: '请检查必填项',
            icon: 'error',
            duration: 2000
        })
    },
    getHospitaldetail(e) {
        wx.navigateTo({
          url: '/pkgCost/pages/ldle-detail/index?id='+e.target.dataset.id,
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this
        if(that.data.active==0){
            that.getldleList()
        } else {
            that.getDispatch()
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})